import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../provider/user_info.dart';
import 'cart/cart_item.dart';
import '../provider/cart.dart';
import '../utils/dio_util.dart';
import '../widget/my_dialog.dart';
import '../widget/error_page.dart';
import '../widget/empty_page.dart';
import 'cart/top.dart';
import 'cart/manage.dart';
import 'cart/bottom.dart';
import 'cart/recommend.dart';
import '../widget/my_title.dart';

class CartPage extends StatefulWidget {
  CartPage({Key key}) : super(key: key);

  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage>
    with AutomaticKeepAliveClientMixin {
  bool _isEdit = false;

  var checkOutProvider;

  @override
  void initState() {
    super.initState();
    print("cart");
  }


  Future<List<Map<String,dynamic>>> initCart() async{
    return await Future.wait([
      getCartList(),
      getRecommend()
    ]);
  }

  //推荐商品列表
  Future<Map<String, dynamic>> getRecommend() async {
    String api = '/api/mall/product/hot.service';
    DioUtil dio = DioUtil();
    return await dio.get(api, data: {'pageIndex': 1, 'pageSize': 4});
  }


  //购物车列表
  Future<Map<String, dynamic>> getCartList() async {
    String api = '/api/mall/cart/pageList.service';
    DioUtil dio = DioUtil();
    return await dio.get(api);

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text("购物车",style: TextStyle(
              color: Colors.black,
              fontSize: 30.sp,
              fontWeight: FontWeight.bold),),
          centerTitle: true,
    
        ),
        body: FutureBuilder<List<Map<String,dynamic>>>(
          future: initCart(),
          builder: (context, AsyncSnapshot snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return CustomLoaddingDialog(
                    height: 150.0, width: 150, title: '努力加载中');
                break;
              case ConnectionState.done: // -------- 完成态
                if (snapshot.hasError) {
                  // 异常
                  return ErrorPage(error: snapshot.error.toString());
                } else {
                  var cartList=snapshot.data[0];
                  var recommend=snapshot.data[1];
                  // 正常
                  if (cartList['code'] == 200) {
                    var cartListResult=cartList['result'];
                    print('cartListResult:${cartListResult['valid']}');
                    List<String> cartIdList=[];
                    cartListResult['valid'].forEach((val){
                      cartIdList.add(val['mallStoreProduct']['cateId']);
                    });
                    print('cartIdList:${cartIdList}');
//                    var cartListNewResult=cartListResult.map((val){
//                      return val.add({'checked':false});
//                    });
                    return RefreshIndicator(
                        displacement: 20,
                        strokeWidth: 4,
                        color: Colors.red,
                        onRefresh: getCartList,
                        child: cartListResult['valid'].isEmpty
                            ? CustomScrollView(
                                shrinkWrap: true,
                                physics: BouncingScrollPhysics(),
                                slivers: [
                                  SliverToBoxAdapter(
                                    child: Top(),
                                  ),
                                  SliverToBoxAdapter(
                                    child: Manage(
                                      count: 0,
                                    ),
                                  ),
                                  SliverToBoxAdapter(
                                    child: EmptyPage(title: '暂无商品，去添加点什么吧'),
                                  ),
                                  SliverToBoxAdapter(
                                    child: SizedBox(
                                      height:50.h
                                    ),
                                  ),
                                  SliverToBoxAdapter(
                                    child: MyTitle(
                                      title: '热门推荐',
                                      color: Colors.black,
                                    ),
                                  ),
                                  SliverPadding(
                                    padding: EdgeInsets.symmetric(horizontal: 25.w,vertical: 50.w),
                                    sliver: Recommend(recommendList:recommend['result']),
                                  )
                                ],
                              )
                            : Column(
                          children: [
                            Expanded(
                              child: CustomScrollView(
                                physics: BouncingScrollPhysics(),
                                slivers: [
                                  SliverToBoxAdapter(
                                    child: Top(),
                                  ),
                                  SliverToBoxAdapter(
                                    child: Manage(
                                      count: cartListResult['valid'].length,
                                    ),
                                  ),
                                  SliverList(
                                    delegate: new SliverChildBuilderDelegate(
                                            (BuildContext context, int index) {
                                          return CartItem(
                                              itemData: cartListResult['valid'][index]);
                                        }, childCount: cartListResult['valid'].length),
                                  ),
                                ],
                              ),
                            ),Bottom(
                                count: 1,
                                amount: 200.00,
                                cartIdList:cartIdList
                            )
                          ],
                        ));
                  } else if (snapshot.data[0]['code'] != 200) {
                    return ErrorPage(error: snapshot.data[0]['msg']);
                  }else if(snapshot.data[1]['code']!=200){
                    return ErrorPage(error:snapshot.data[1]['msg']);
                  }
                }
                break;
              default:
                break;
            }
          },
        ));
  }

  @override
  bool get wantKeepAlive => true;
}
